package com.ingenio.siot.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ingenio.siot.adapter.MovilAdapter;
import com.ingenio.siot.adapter.TipoMovilAdapter;
import com.ingenio.siot.entity.Movil;
import com.ingenio.siot.entity.TipoMovil;

/**
 * Servlet implementation class BuscarMovilesServlet
 */
@WebServlet("/BuscarMoviles")
public class BuscarMovilesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BuscarMovilesServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer id = Integer.parseInt(request.getParameter("id"));
		try{
			
			TipoMovilAdapter tma = new TipoMovilAdapter();
			TipoMovil tm = tma.devolverTipoMovil(id);
		
			MovilAdapter ma = new MovilAdapter();
			List<Movil> moviles = ma.devolverMovilesdesdeTipoMovil(tm);
						
			JSONObject json = new JSONObject();
			JSONArray ja = new JSONArray();
			
			for (Movil m : moviles) {
			   JSONObject jo = new JSONObject();
			   jo.put("id", m.getIdMovil());
			   jo.put("desc", m.getDescMovil() +" - "+m.getPatente());
			   ja.put(jo);
			}
			
			json.put("moviles", ja);
			response.setContentType("application/json");
			response.getWriter().write(json.toString());
		}
		catch(Exception e){
			
		}
	}

}
